<?php

namespace Admin\Controller;
use Common\Controller\AdminbaseController;
/**
 * 代理商管理
 * 
 * @author
 * @version 
 */
class AgentController extends AdminbaseController
{
	protected $users_obj;
	
	function _initialize() {
		parent::_initialize();
		$this->users_obj = D("Common/Users");
	
	}
	
	
	/**
	 * The default action - show the home page
	 */
    public function index()
    {
    	$where["user_type"]=2;
    	$where["father_id"]=0;
    	$count=$this->users_obj->where($where)->count();
    	$page = $this->page($count, 20);
    	
    	$join=C(DB_PREFIX)."agent as A on A.agent_uid=U.id";
    	$users = $this->users_obj
    	->alias("U")
    	->join($join)
    	->where($where)
    	->order("create_time DESC")
    	->limit($page->firstRow . ',' . $page->listRows)
    	->select();
    	
    	$this->get_area();
    	$this->assign("page", $page->show('Admin'));
    	$this->assign("users",$users);
    	$this->display();
    }
    /**
     *  删除
     */
    function delete(){
    	$id = intval(I("get.id"));
    	if($id==1){
    		$this->error("最高管理员不能删除！");
    	}
    	$user=$this->users_obj->where("id=$id")->delete();
    	$daili=M("Agent")->where("agent_uid=$id")->delete();
    	if ($user&&daili) {
    		$this->success("删除成功！");
    	} else {
    		$this->error("删除失败！");
    	}
    }
    
    
    public function add()
    {
    	$this->display();
    }
    function add_post(){
    	if(IS_POST){
    	
    			$agent_name=I("post.agent_name","","trim");
    			$agent_tel=I("post.agent_tel","","trim");
    			$agent_ren=I("post.agent_ren","","trim");
    			$agent_dome=I("post.agent_dome","","trim");
    			$province=I("post.s_province",0,"intval");
    			$city=I("post.s_city",0,"intval");
    			$county=I("post.s_county",0,"intval");
    			if(empty($agent_name)){$this->error("代理商名称不能为空"); }
    			if(empty($agent_tel)){$this->error("联系电话不能为空"); }
    			if($province==0){$this->error("必须选择省份");}
    			if($city==0){$this->error("必须选择城市");}
    			if($county==0){$this->error("必须选择县区");}
    			$preg=preg_match('/^(13\d{1}|15[03689]|18[03689])\d{8}$^(\d{3}-)(\d{8})$|^(\d{4}-)(\d{7})$|^(\d{4}-)(\d{8})$|/',$agent_tel);
    			if(!$preg) $this->error("联系电话格式不正确");
    			if(empty($agent_ren)){$this->error("联系人不能为空"); }
    			if(empty($agent_dome)){$this->error("请填写域名前缀"); }
    			$preg=preg_match("/^[A-Za-z0-9]{2,15}$/",$agent_dome);
    			if(!preg)$this->error("域名前缀只能为数字和字母");
    			//判断域名是否存在
    			$isDome=M("Agent")->where(array("agent_dome"=>$agent_dome))->find();
    			if($isDome)$this->error("已经存在此二级域名，请修改");
    			$_POST["user_type"]=2; //代理类型
    			if ($this->users_obj->create()) {
    				$result=$this->users_obj->add();
    				if ($result!==false) {
    					$agent=M("Agent");
    					$data["agent_uid"]=$result;
    					$data["agent_name"]=$agent_name;
    					$data["agent_tel"]=$agent_tel;
    					$data["agent_ren"]=$agent_ren;
    					$data["agent_dome"]=$agent_dome;
    					$data["join_time"]=time();
    					$data["s_province"]=$province;
    					$data["s_city"]=$city;
    					$data["s_county"]=$county;
    					$agent->add($data);
    					$this->success("添加成功！", U("Agent/index"));
    				} else {
    					$this->error("添加失败！");
    				}
    			} else {
    				$this->error($this->users_obj->getError());
    			}
    		
    	}
    }
    
    function edit(){
    	$id= intval(I("get.id"));
    	if($id==0) {$this->error("不存在此用户");}
		$where["id"]=$id;
		$join=C("DB_PREFIX")."agent as A on U.id=A.agent_uid";
    	$user=$this->users_obj->alias("U")->join($join)->where($where)->find();
    	
    	$this->assign("user",$user);
    	$this->display();
    }
    
    function edit_post(){
    	if (IS_POST) {
    		if($_POST['id']>0){
    			if(empty($_POST['user_pass'])){
    				unset($_POST['user_pass']);
    			}
    			//获取代理的信息
    			$where["agent_uid"]=array("neq",intval($_POST['id']));
    			$where["agent_dome"]=$_POST["agent_dome"];
    			$agentData=M("Agent")->where($where)->find();
				if($agentData)$this->error("当前域名已经存在");
    			if ($this->users_obj->create()) {
    				$result=$this->users_obj->save();
    				if ($result!==false) {
    					$P=I("post.");
    					$Awhere["agent_uid"]=intval($_POST['id']);
    					$data["agent_name"]=$P["agent_name"];
    					$data["agent_tel"]=$P["agent_tel"];
    					$data["agent_ren"]=$P["agent_ren"];
    					$data["agent_dome"]=$P["agent_dome"];
    					M("Agent")->where($Awhere)->save($data);
    					$this->success("保存成功！");
    				} else {
    					$this->error("保存失败！");
    				}
    			} else {
    				$this->error($this->users_obj->getError());
    			}
    		}else{
    			$this->error("非法操作");
    		}
    			
    	}
    }
    
    
    
    
    public function role()
    {
    	$this->auth_access_model = D("Common/AuthAccessd");
    	//角色ID
    	$roleid = intval(I("get.id"));
    	$roleid=1;
    	if (!$roleid) {
    		$this->error("参数错误！");
    	}
    	import("Tree");
    	$menu = new \Tree();
    	$menu->icon = array('│ ', '├─ ', '└─ ');
    	$menu->nbsp = '&nbsp;&nbsp;&nbsp;';
    	$result = $this->initMenu();
    	$newmenus=array();
    	$priv_data=$this->auth_access_model->where(array("role_id"=>$roleid))->getField("rule_name",true);//获取权限表数据
    	foreach ($result as $m){
    		$newmenus[$m['id']]=$m;
    		 
    	}
    	
    	foreach ($result as $n => $t) {
    		$result[$n]['checked'] = ($this->_is_checked($t, $roleid, $priv_data)) ? ' checked' : '';
    		$result[$n]['level'] = $this->_get_level($t['id'], $newmenus);
    		$result[$n]['parentid_node'] = ($t['parentid']) ? ' class="child-of-node-' . $t['parentid'] . '"' : '';
    	}
    	$str = "<tr id='node-\$id' \$parentid_node>
                       <td style='padding-left:30px;'>\$spacer<input type='checkbox' name='menuid[]' value='\$id' level='\$level' \$checked onclick='javascript:checknode(this);'> \$name</td>
	    			</tr>";
    	$menu->init($result);
    	$categorys = $menu->get_tree(0, $str);
    	
    	$this->assign("categorys", $categorys);
    	$this->assign("roleid", $roleid);
    	$this->display();
    	
    
    }
    /**
     * 角色授权
     */
    public function role_post() {
    	 
    	if (IS_POST) {
    		$roleid = intval(I("post.roleid"));
    		$roleid=1;
    		if(!$roleid){
    			$this->error("需要授权的角色不存在！");
    		}
    		if (is_array($_POST['menuid']) && count($_POST['menuid'])>0) {
    			$this->auth_access_model = D("Common/AuthAccessd");
    			$menu_model=M("Menu");
    			$auth_rule_model=M("AuthRule");
    			$this->auth_access_model->where(array("role_id"=>$roleid,'type'=>'admin_url'))->delete();
    			foreach ($_POST['menuid'] as $menuid) {
    				$menu=$menu_model->where(array("id"=>$menuid))->field("app,model,action")->find();
    				if($menu){
    					$app=$menu['app'];
    					$model=$menu['model'];
    					$action=$menu['action'];
    					$name=strtolower("$app/$model/$action");
    					$this->auth_access_model->add(array("role_id"=>$roleid,"rule_name"=>$name,'type'=>'admin_url'));
    				}
    			}
    
    			$this->success("授权成功！", U("Agent/role"));
    		}else{
    			//当没有数据时，清除当前角色授权
    			$this->auth_access_model->where(array("role_id" => $roleid))->delete();
    			$this->error("没有接收到数据，执行清除授权成功！");
    		}
    	}
    }
    
    
    
    /**
     *  检查指定菜单是否有权限
     * @param array $menu menu表中数组
     * @param int $roleid 需要检查的角色ID
     */
    private function _is_checked($menu, $roleid, $priv_data) {
    	 
    	$app=$menu['app'];
    	$model=$menu['model'];
    	$action=$menu['action'];
    	$name=strtolower("$app/$model/$action");
    	if($priv_data){
    		if (in_array($name, $priv_data)) {
    			return true;
    		} else {
    			return false;
    		}
    	}else{
    		return false;
    	}
    	 
    }
    
    /**
     * 获取菜单深度
     * @param $id
     * @param $array
     * @param $i
     */
    protected function _get_level($id, $array = array(), $i = 0) {
    
    	if ($array[$id]['parentid']==0 || empty($array[$array[$id]['parentid']]) || $array[$id]['parentid']==$id){
    		return  $i;
    	}else{
    		$i++;
    		return $this->_get_level($array[$id]['parentid'],$array,$i);
    	}
    
    }
    
    public function area()
    {
    	$fup=I("post.fup",0,"intval");
    	
    	$data=M("area")->where("fup=$fup")->getField("fid,name");
    	if($data)
    	{
    		$str="";
    		foreach($data as $key=>$val)
    		{	
    			$str.="<option value='{$key}'>{$val}</option>";
    		}
    		$this->success($str);
    	}else{
    	$this->error("未获取到数据");
    		}
    }
    
    public function get_area()
    {
    	$areaData=F("area_qy");
    	if(!is_array($areaData))
    	{
    		$areaData=M("area")->getField("fid,name");
    		F("area_qy",$areaData);
    	}
    	
    	$this->assign("areData",$areaData);
    }
    
    
    
    
}